/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rukopisyimport.foxml.images;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import cz.mzk.rehan.commons.FileUtils;
import cz.mzk.rehan.commons.PropertyLoader;
import cz.mzk.rehan.commons.RandomBasedUuidGenerator;
import cz.mzk.rehan.commons.UuidGenerator;
import java.io.FilenameFilter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Rehanek (rehan@mzk.cz)
 */
public class ImageDownloader {

    private static final Logger logger = Logger.getLogger(ImageDownloader.class.getName());
    private static final String PROP_PICTURES_DIR = "Convertor.downloadedPicturesDir";
    private final File pictureDir;
    private final UuidGenerator uuidGenerator;

    public ImageDownloader(Properties properties, boolean clearPictureDir) {
        //uuidGenerator = EthAddrUuidGenerator.instanceOf(properties);
        uuidGenerator = RandomBasedUuidGenerator.instanceOf();
        PropertyLoader propertyLoader = new PropertyLoader(properties);
        pictureDir = propertyLoader.loadDir(PROP_PICTURES_DIR);
        if (clearPictureDir) {
            clearPictureDir();
        }
    }

    private void clearPictureDir() {
        File[] listFiles = pictureDir.listFiles(new FilenameFilter() {

            private static final String suffix = ".jpg";

            public boolean accept(File dir, String name) {
                return name.endsWith(suffix);
            }
        });
        for (File file : listFiles) {
            if (!file.delete()) {
                logger.log(Level.WARNING, "cannot remove file ''{0}''", file.getAbsolutePath());
            }
        }
    }

    public File downloadAndSaveFile(String imageUrl) throws IOException {
        File outFile = createOutFile(imageUrl);
        downloadIfNotFound(imageUrl, outFile);
        return outFile;
    }

    private void downloadIfNotFound(String imageUrl, File outFile) throws IOException {
        if (outFile.exists() && outFile.getTotalSpace() != 0) {
            System.out.println("already downloaded " + imageUrl);
            return;
        } else {
            System.out.println("downloading " + imageUrl);
            byte[] data = downloadFile(imageUrl);
            FileUtils.saveDataToFile(data, outFile);
        }
    }

    private byte[] downloadFile(String imageUrl) throws MalformedURLException, IOException {
        URL url = new URL(imageUrl);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(0);
        InputStream in = new BufferedInputStream(connection.getInputStream());
        int contentLength = connection.getContentLength();
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1) {
                break;
            }
            offset += bytesRead;
        }
        in.close();
        return data;
    }

    private File createOutFile(String imageUrl) {
        String filename = pictureDir.getAbsolutePath()
                + File.separator
                + nameFromUrl(imageUrl);
        return new File(filename);
    }

    private String nameFromUrl(String imageUrl) {
        String[] tokens = imageUrl.split("/");
        return tokens[tokens.length - 1];
    }
}
